<?php
class Kernel extends Db {

    public $t = null;
    public $setting = null;
    public $isAdmin = false;
    public $admin = null;

    public function __construct() {
        $this->connection();
        $this->init();
        $this->t = C("Template");
    }

    public function display( $file ) {
        return $this->t->display( $file );
    }

    private function init() {
        if ( $this->setting != null ) {
            return;
        }
        $this->table = 'setting';
        $setting = $this->Cache()->get( 'setting' );

        @date_default_timezone_set( $setting[ 'timezone' ] );
        $setting[ 'weburl' ] = !empty( $setting[ 'weburl' ] ) ? $setting[ 'weburl' ] : getRequest();
        $this->setting = $setting;
    }

    # 读取目录
    public function getList( $path = null ) {
        $path = WEBROOT . $path;
        $arr = array();
        foreach ( glob( $path ) as $dir ) {
            if ( is_dir( $dir ) ) {
                $tmp = explode( "/", $dir );
                $name = end( $tmp );
                $arr[ $name ] = $dir;
            }
        }
        return $arr;
    }

    public function url( $c, $a = null, $args = null, $anchor = null ) {
        $PHP_SELF = str_replace( "index.php", "", getRequest( 'SCRIPT_NAME' ) );
        if( $c == null ) return $this->setting[ 'weburl' ] . $PHP_SELF;

        $a = $a == null ? '' : "&a={$a}";
        $url = "{$PHP_SELF}?c={$c}{$a}";

        if ( null != $args && is_array( $args ) ) {
            foreach ( $args as $key => $arg ) $url .= "&{$key}={$arg}";
        }
        if ( null != $args && is_string( $args ) ) {
            $url .= "&{$args}";
        }
        if ( null != $anchor ) $url .= "#" . $anchor;
        return $this->setting[ 'weburl' ] . $url;
    }

    /**
     * 魔术函数
     */
    public function __call( $name, $args ) {
        $name = strtolower( $name );
        $file = WEBLIB . $name . '.php';
        if ( file_exists( $file ) ) {
            require_once $file;
        }
        if ( class_exists( $name ) ) {
            $obj = new $name();
            return $obj->input( $this, $args );
        }
        showError( "{$name} 不存在<br />" . getRequest('REQUEST_URI'), 'system' );
    }
}